<?php

//就近 www.jiujin.me
global $_W, $_GPC;
$operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
m('order')->checkisclose();
if ($operation == 'display') {
	$pindex = max(1, intval($_GPC['page']));
	$psize = 20;
	$status = $_GPC['status'];
	$sendtype = !isset($_GPC['sendtype']) ? 0 : $_GPC['sendtype'];
	$condition = " o.uniacid = :uniacid ";
	$paras = array(':uniacid' => $_W['uniacid']);
        $starttime = empty($_GPC['time']['start']) ? strtotime('-1 month') : strtotime($_GPC['time']['start']);
        $endtime = empty($_GPC['time']['end']) ? TIMESTAMP : strtotime($_GPC['time']['end']);
        if ($_GPC['searchtime'] == '1') {
                $condition .= " AND o.createtime >= :starttime AND o.createtime <= :endtime ";
                $paras[':starttime'] = $starttime;
                $paras[':endtime'] = $endtime;
        }
	if ($_GPC['paytype'] != '') {
		if ($_GPC['paytype'] == '2') {
			$condition .= " AND ( o.paytype =21 or o.paytype=22 or o.paytype=23 )";
		} else {
			$condition .= " AND o.paytype =" . intval($_GPC['paytype']);
		}
	}
	if (!empty($_GPC['realname'])) {
		$_GPC['realname'] = trim($_GPC['realname']);
		$params[':realname'] = "%{$_GPC['realname']}%";
               	$userid =pdo_fetchall("select id  from " . tablename('ewei_shop_member') ." where realname like :realname or nickname like :realname or mobile like :realname ORDER BY id DESC ",$params);
                if($userid){
                    foreach($userid as $key=>$value){
                    $userid[$key]=$value['id'];
                    }
                    $ids=implode(',',$userid);
                }
                $condition .= " AND o.mid in ('{$ids}')";
	}
	if (!empty($_GPC['ordersn'])) {
		$_GPC['ordersn'] = trim($_GPC['ordersn']);
		$condition .= " AND o.ordersn LIKE '%{$_GPC['ordersn']}%'";
	}
	if (!empty($_GPC['expresssn'])) {
		$_GPC['expresssn'] = trim($_GPC['expresssn']);
		$condition .= " AND o.expresssn LIKE '%{$_GPC['expresssn']}%'";
	}
	if (!empty($_GPC['member'])) {
		$_GPC['member'] = trim($_GPC['member']);
		$condition .= " AND (m.realname LIKE '%{$_GPC['member']}%' or m.mobile LIKE '%{$_GPC['member']}%' or m.nickname LIKE '%{$_GPC['member']}%' " . " or a.realname LIKE '%{$_GPC['member']}%' or a.mobile LIKE '%{$_GPC['member']}%' or o.carrier LIKE '%{$_GPC['member']}%')";
	}
	if (!empty($_GPC['xiaoshop'])) {
		$_GPC['xiaoshop'] = trim($_GPC['xiaoshop']);
		$p =array(':xiaoshop'=>"%{$_GPC['xiaoshop']}%");
               	$userid =pdo_fetchall("select id  from " . tablename('ewei_shop_member') ." where realname like :xiaoshop or nickname like :xiaoshop or mobile like :xiaoshop ORDER BY id DESC ",$p);
                if($userid){
                    $condition .= " AND (";
                    foreach($userid as $key=>$value){
                       $lastkey=$key;
                    }
                    foreach($userid as $key=>$value){
                        if($lastkey==$key){
                         $condition .= " o.mid={$value['id']} ";
                        }else{
                         $condition .= " o.mid={$value['id']} or";   
                        }
                    }
                    $condition .= " ) ";
                }
	}
        //gwj 2016/10/11
        if (!empty($_GPC['openid'])) {
		$_GPC['openid'] = trim($_GPC['openid']);
                $condition .= " AND m.openid LIKE '%{$_GPC['openid']}%'";
	}
        if($status == 7 ){
            $free_log=pdo_fetchall('select * from '.tablename('ewei_shop_dispatchprice_free_log').'where uniacid=:uniacid order by id desc',array(':uniacid'=>$_W['uniacid']));
            foreach($free_log as $key=>$value){
                $rea= pdo_fetch('select * from ' . tablename('ewei_shop_member_address') . ' where uniacid=:uniacid and openid=:openid limit 1', array(':uniacid' => $_W['uniacid'], ':openid' => $value['openid']));
                $free_log[$key]['realname']=$rea['realname'];
                $dispatch = pdo_fetch("SELECT * FROM " . tablename('ewei_shop_dispatch') . " WHERE id = :id and uniacid=:uniacid", array(':id' => $value['dispatchid'], ':uniacid' => $_W['uniacid']));
                $free_log[$key]['dispatchname']=$dispatch['dispatchname'];
                $free_log[$key]['createtime']=date('Y-m-d H:i:s',$value['createtime']);
            }
            include $this->template('web/allorder/normal_free_log');
            exit;
        }
	if ($status != '') {
		if ($status == -1) {
			ca('order.view.status_1');
		} else {
			ca('order.view.status' . intval($status));
		}
		if ($status == '-1') {
			//$condition .= " AND o.status=-1 and r.status!=1 and o.TotalId!=1";
                    $condition .= " AND o.status=-1 and o.TotalId!=1";
		} else {
			if ($status == '4') {
				$condition .= " AND o.refundid<>0 and r.status=0 and o.TotalId!=1";
			} else {
				if ($status == '5') {
					$condition .= " AND r.status=1";
				} else {
                                    if($status == '6'){
                                        $condition .= " AND o.mid<>0 ";
                                    }else{
                                        if($status == '3'){
					$condition .= " AND o.status = '" . intval($status) . "' and o.TotalId!=1";
                                        }else{
                                            if($status == '2'){
                                              $condition .= " AND o.status = '" . intval($status) . "' and o.TotalId!=1";  
                                            }else{
                                              if($status == '1'){
                                              $condition .= " AND o.status = '" . intval($status) . "' and o.TotalId!=1 and o.refundid=0"; 
                                              }else{
                                                  if($status === '0'){
                                                   $condition .= " AND o.status = '" . intval($status) . "' and o.TotalId<2";    
                                                  }else{
                                                   $condition .= " AND o.status = '" . intval($status) . "'";    
                                                  }
                                              }
                                            }
                                        }
                                    }
				}
			}
		}
        }else{
            ca('order.view');
        }
	$agentid = intval($_GPC['agentid']);
	$p = p('commission');
	$level = 0;
	if ($p) {
		$cset = $p->getSet();
		$level = intval($cset['level']);
	}
	$olevel = intval($_GPC['olevel']);
	if (!empty($agentid) && $level > 0) {
		$agent = $p->getInfo($agentid, array());
		if (!empty($agent)) {
			$agentLevel = $p->getLevel($agentid);
		}
		
		if (empty($olevel)) {
			if ($level >= 1) {
				$condition .= ' and  ( o.agentid=' . intval($_GPC['agentid']);
			}
			if ($level >= 2 && $agent['level2'] > 0) {
				$condition .= " or o.agentid in( " . implode(',', array_keys($agent['level1_agentids'])) . ")";
			}
			if ($level >= 3 && $agent['level3'] > 0) {
				$condition .= " or o.agentid in( " . implode(',', array_keys($agent['level2_agentids'])) . ")";
			}
			if ($level >= 1) {
				$condition .= ")";
			}
		} else {
			if ($olevel == 1) {
				$condition .= ' and  o.agentid=' . intval($_GPC['agentid']);
			} else {
				if ($olevel == 2) {
					if ($agent['level2'] > 0) {
						$condition .= " and o.agentid in( " . implode(',', array_keys($agent['level1_agentids'])) . ")";
					} else {
						$condition .= " and o.agentid in( 0 )";
					}
				} else {
					if ($olevel == 3) {
						if ($agent['level3'] > 0) {
							$condition .= " and o.agentid in( " . implode(',', array_keys($agent['level2_agentids'])) . ")";
						} else {
							$condition .= " and o.agentid in( 0 )";
						}
					}
				}
			}
		}
	}
	$sql = "select o.* , a.realname,a.mobile,a.province,a.city,a.area,a.address, d.dispatchname,r.status as refundstatus from " . tablename('ewei_shop_order') . " o" . " left join " . tablename('ewei_shop_order_refund') . " r on r.orderid=o.id and ifnull(r.status,-1)<>-1" . " left join " . tablename('ewei_shop_member') . " m on m.openid=o.openid" . " left join " . tablename('ewei_shop_member_address') . " a on o.addressid = a.id " . " left join " . tablename('ewei_shop_dispatch') . " d on d.id = o.dispatchid " . " where {$condition} ORDER BY o.createtime DESC,o.status DESC  ";
        if (empty($_GPC['export'])) {
		$sql .= "LIMIT " . ($pindex - 1) * $psize . ',' . $psize;
	}
	$list = pdo_fetchall($sql, $paras);
	$paytype = array('0' => array('css' => 'default', 'name' => '未支付'), '1' => array('css' => 'danger', 'name' => '余额支付'), '11' => array('css' => 'default', 'name' => '后台付款'), '2' => array('css' => 'danger', 'name' => '在线支付'), '21' => array('css' => 'success', 'name' => '微信支付'), '22' => array('css' => 'warning', 'name' => '支付宝支付'), '23' => array('css' => 'warning', 'name' => '银联支付'), '3' => array('css' => 'primary', 'name' => '货到付款'));
	$orderstatus = array('-1' => array('css' => 'default', 'name' => '已关闭'), '0' => array('css' => 'danger', 'name' => '待付款'), '1' => array('css' => 'info', 'name' => '待发货'), '2' => array('css' => 'warning', 'name' => '待收货'), '3' => array('css' => 'success', 'name' => '已完成'));
	foreach ($list as &$value) {
                $userinfo = pdo_fetch('select * from ' . tablename('ewei_shop_member') . ' where uniacid=:uniacid and id=:id limit 1', array(':uniacid' => $_W['uniacid'], ':id' => $value['mid']));
                $value['shopname']=$userinfo['nickname']."的小店";
		$s = $value['status'];
		$value['statusvalue'] = $s;
		$value['statuscss'] = $orderstatus[$value['status']]['css'];
		$value['status'] = $orderstatus[$value['status']]['name'];
		if ($s == -1) {
			if ($value['refundstatus'] == 1) {
				$value['status'] = '已退款';
			}
		}
		$p = $value['paytype'];
		$value['css'] = $paytype[$p]['css'];
		$value['paytype'] = $paytype[$p]['name'];
		$value['dispatchname'] = empty($value['addressid']) ? '自提' : $value['dispatchname'];
		if (empty($value['dispatchname'])) {
			$value['dispatchname'] = '快递';
		}
		if ($value['isverify'] == 1) {
			$value['dispatchname'] = "线下核销";
		}
		if ($value['dispatchtype'] == 1 || !empty($value['isverify'])) {
			$carrier = iunserializer($value['carrier']);
			if (is_array($carrier)) {
				$value['realname'] = $carrier['carrier_realname'];
				$value['mobile'] = $carrier['carrier_mobile'];
			}
		} else {
			$value['address'] = $value['province'] . " " . $value['city'] . " " . $value['area'] . " " . $value['address'];
		}
		$order_goods = pdo_fetchall('select g.credit,g.id,g.title,g.thumb,g.goodssn,og.goodssn as option_goodssn, g.productsn,og.productsn as option_productsn, og.total,og.price,og.optionname as optiontitle, og.realprice from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join ' . tablename('ewei_shop_goods') . ' g on g.id=og.goodsid ' . ' where og.uniacid=:uniacid and og.orderid=:orderid ', array(':uniacid' => $_W['uniacid'], ':orderid' => $value['id']));
		$goods = '';
		$credit = '';
		foreach ($order_goods as &$og) {
			$goods .= "" . $og['title'] . "\r\n";
			if (!empty($og['optiontitle'])) {
				$goods .= " 规格: " . $og['optiontitle'];
			}
			if (!empty($og['option_goodssn'])) {
				$og['goodssn'] = $og['option_goodssn'];
			}
			if (!empty($og['option_productsn'])) {
				$og['productsn'] = $og['option_productsn'];
			}
			if (!empty($og['goodssn'])) {
				$goods .= ' 商品编号: ' . $og['goodssn'];
			}
			if (!empty($og['productsn'])) {
				$goods .= ' 商品条码: ' . $og['productsn'];
			}
			$goods .= ' 单价: ' . $og['price'] / $og['total'] . ' 折扣后: ' . $og['realprice'] / $og['total'] . ' 数量: ' . $og['total'] . ' 总价: ' . $og['price'] . " 折扣后: " . $og['realprice'] . "\r\n ";
			//gmm
			$credit += $og['credit'];
		}
		//gmm 2015-11-26
		if($s != -1){
			$value['credit'] = $credit;
		}else{
			$value['credit'] = 0;
		}
		$totalcredit += $value['credit'];
		unset($og);
		$value['goods'] = set_medias($order_goods, 'thumb');
		$value['goods_str'] = $goods;
		if (!empty($agentid) && $level > 0) {
			$commission_level = 0;
			if ($value['agentid'] == $agentid) {
				$value['level'] = 1;
				$level1_commissions = pdo_fetchall('select commission1  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid ' . ' where og.orderid=:orderid and o.agentid= ' . $agentid . "  and o.uniacid=:uniacid", array(':orderid' => $value['id'], ':uniacid' => $_W['uniacid']));
				foreach ($level1_commissions as $c) {
					$commission = iunserializer($c['commission1']);
					$commission_level += isset($commission['level' . $agentLevel['id']]) ? $commission['level' . $agentLevel['id']] : $commission['default'];
				}
			} else {
				if (in_array($value['agentid'], array_keys($agent['level1_agentids']))) {
					$value['level'] = 2;
					if ($agent['level2'] > 0) {
						$level2_commissions = pdo_fetchall('select commission2  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid ' . ' where og.orderid=:orderid and  o.agentid in ( ' . implode(',', array_keys($agent['level1_agentids'])) . ")  and o.uniacid=:uniacid", array(':orderid' => $value['id'], ':uniacid' => $_W['uniacid']));
						foreach ($level2_commissions as $c) {
							$commission = iunserializer($c['commission2']);
							$commission_level += isset($commission['level' . $agentLevel['id']]) ? $commission['level' . $agentLevel['id']] : $commission['default'];
						}
					}
				} else {
					if (in_array($value['agentid'], array_keys($agent['level2_agentids']))) {
						$value['level'] = 3;
						if ($agent['level3'] > 0) {
							$level3_commissions = pdo_fetchall('select commission3 from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on o.id = og.orderid ' . ' where og.orderid=:orderid and  o.agentid in ( ' . implode(',', array_keys($agent['level2_agentids'])) . ")  and o.uniacid=:uniacid", array(':orderid' => $value['id'], ':uniacid' => $_W['uniacid']));
							foreach ($level3_commissions as $c) {
								$commission = iunserializer($c['commission3']);
								$commission_level += isset($commission['level' . $agentLevel['id']]) ? $commission['level' . $agentLevel['id']] : $commission['default'];
							}
						}
					}
				}
			}
			$value['commission'] = $commission_level;
			/*
			 *  gmm
			 *  修改：佣金总额
			 *  时间：2015年11月26日
			 */
			$totalcommission += $value['commission'];
		}
	}
	unset($value);
        if($_GPC['submit_modal'] == "导出模板"){
        ca('order.op.export');
	plog('order.op.export', '导出订单');
        $columns =array(array('title' => '订单编号', 'field' => 'ordersn', 'width' => 24),array('title' => '快递公司', 'field' => 'expresscom', 'width' => 24),array('title' => '快递单号', 'field' => 'expresssn', 'width' => 24));
        m('excel')->export(" ", array("title" => "普通待发货订单模板-" . date('Y-m-d-H-i', time()), "columns" => $columns));
        }
        if($_GPC['submit_expro'] == "批量发货"){
        $info=m('excel')->import("import_expro");
        foreach($info as $key=>$value){
        $value[0]=trim($value[0]);$value[1]=trim($value[1]);$value[2]=trim($value[2]);
        if($value[1]=="顺丰"){$express="shunfeng";}if($value[1]=="申通"){$express="shentong";}if($value[1]=="韵达快运"){$express="yunda";}if($value[1]=="天天快递"){$express="tiantian";}if($value[1]=="圆通速递"){$express="yuantong";}
        if($value[1]=="中通速递"){$express="zhongtong";}if($value[1]=="ems快递"){$express="ems";}if($value[1]=="汇通快运"){$express="huitongkuaidi";}if($value[1]=="全峰快递"){$express="quanfengkuaidi";}if($value[1]=="宅急送"){$express="zhaijisong";}
        if($value[1]=="aae全球专递"){$express="aae";}if($value[1]=="安捷快递"){$express="anjie";}if($value[1]=="安信达快递"){$express="anxindakuaixi";}if($value[1]=="彪记快递"){$express="biaojikuaidi";}if($value[1]=="bht"){$express="bht";}
        if($value[1]=="百福东方国际物流"){$express="baifudongfang";}if($value[1]=="中国东方（COE）"){$express="coe";}if($value[1]=="长宇物流"){$express="changyuwuliu";}if($value[1]=="大田物流"){$express="datianwuliu";}if($value[1]=="德邦物流"){$express="debangwuliu";}
        if($value[1]=="dhl"){$express="dhl";}if($value[1]=="dpex"){$express="dpex";}if($value[1]=="d速快递"){$express="dsukuaidi";}if($value[1]=="递四方"){$express="disifang";}if($value[1]=="fedex（国外）"){$express="fedex";}
        if($value[1]=="飞康达物流"){$express="feikangda";}if($value[1]=="凤凰快递"){$express="fenghuangkuaidi";}if($value[1]=="飞快达"){$express="feikuaida";}if($value[1]=="国通快递"){$express="guotongkuaidi";}if($value[1]=="港中能达物流"){$express="ganzhongnengda";}  
        if($value[1]=="广东邮政物流"){$express="guangdongyouzhengwuliu";}if($value[1]=="共速达"){$express="gongsuda";}if($value[1]=="恒路物流"){$express="hengluwuliu";}if($value[1]=="华夏龙物流"){$express="huaxialongwuliu";}if($value[1]=="海红"){$express="haihongwangsong";}
        if($value[1]=="海外环球"){$express="haiwaihuanqiu";}if($value[1]=="佳怡物流"){$express="jiayiwuliu";}if($value[1]=="京广速递"){$express="jinguangsudikuaijian";}if($value[1]=="急先达"){$express="jixianda";}if($value[1]=="佳吉物流"){$express="jjwl";}
        if($value[1]=="加运美物流"){$express="jymwl";}if($value[1]=="金大物流"){$express="jindawuliu";}if($value[1]=="嘉里大通"){$express="jialidatong";}if($value[1]=="晋越快递"){$express="jykd";}if($value[1]=="快捷速递"){$express="kuaijiesudi";}
        if($value[1]=="联邦快递（国内）"){$express="lianb";}if($value[1]=="联昊通物流"){$express="lianhaowuliu";}if($value[1]=="龙邦物流"){$express="longbanwuliu";}if($value[1]=="立即送"){$express="lijisong";}if($value[1]=="乐捷递"){$express="lejiedi";}
        if($value[1]=="民航快递"){$express="minghangkuaidi";}if($value[1]=="美国快递"){$express="meiguokuaidi";}if($value[1]=="门对门"){$express="menduimen";}if($value[1]=="OCS"){$express="ocs";}if($value[1]=="配思货运"){$express="peisihuoyunkuaidi";}
        if($value[1]=="全晨快递"){$express="quanchenkuaidi";}if($value[1]=="全际通物流"){$express="quanjitong";}if($value[1]=="全日通快递"){$express="quanritongkuaidi";}if($value[1]=="全一快递"){$express="quanyikuaidi";}if($value[1]=="如风达"){$express="rufengda";}
        if($value[1]=="三态速递"){$express="santaisudi";}if($value[1]=="盛辉物流"){$express="shenghuiwuliu";}if($value[1]=="速尔物流"){$express="sue";}if($value[1]=="盛丰物流"){$express="shengfeng";}if($value[1]=="赛澳递"){$express="saiaodi";}
        if($value[1]=="天地华宇"){$express="tiandihuayu";}if($value[1]=="tnt"){$express="tnt";}if($value[1]=="ups"){$express="ups";}if($value[1]=="万家物流"){$express="wanjiawuliu";}if($value[1]=="文捷航空速递"){$express="wenjiesudi";}
        if($value[1]=="伍圆"){$express="wuyuan";}if($value[1]=="万象物流"){$express="wxwl";}if($value[1]=="新邦物流"){$express="xinbangwuliu";}if($value[1]=="信丰物流"){$express="xinfengwuliu";}if($value[1]=="亚风速递"){$express="yafengsudi";}
        if($value[1]=="一邦速递"){$express="yibangwuliu";}if($value[1]=="优速物流"){$express="youshuwuliu";}if($value[1]=="邮政包裹挂号信"){$express="youzhengguonei";}if($value[1]=="邮政国际包裹挂号信"){$express="youzhengguoji";}
        if($value[1]=="远成物流"){$express="yuanchengwuliu";}if($value[1]=="源伟丰快递"){$express="yuanweifeng";}if($value[1]=="元智捷诚快递"){$express="yuanzhijiecheng";}if($value[1]=="运通快递"){$express="yuntongkuaidi";}if($value[1]=="越丰物流"){$express="yuefengwuliu";}
        if($value[1]=="源安达"){$express="yad";}if($value[1]=="银捷速递"){$express="yinjiesudi";}if($value[1]=="中铁快运"){$express="zhongtiekuaiyun";}if($value[1]=="中邮物流"){$express="zhongyouwuliu";} if($value[1]=="忠信达"){$express="zhongxinda";}if($value[1]=="芝麻开门"){$express="zhimakaimen";}
        $item = pdo_fetch("SELECT * FROM " . tablename('ewei_shop_order') . " WHERE ordersn = :ordersn and uniacid=:uniacid", array(':ordersn' =>$value[0], ':uniacid' => $_W['uniacid']));
        if($item['status']==1 && empty($item['refundid']) && !empty($value[0]) && !empty($value[1]) && !empty($value[2]) && !empty($item)){
        pdo_update('ewei_shop_order',array('status' => 2,'remark' => trim($_GPC['remark']),"expresscom"=>$value[1],"expresssn"=>$value[2],"sendtime"=>time(),'express' => $express), array("ordersn"=>$value[0], 'uniacid' => $_W['uniacid'])); 
        m('notice')->sendOrderMessage($item['id']);
	plog('order.op.send', "订单发货 ID: {$item['id']} 订单号: {$value[0]} <br/>快递公司: {$value[1]} 快递单号: {$value[2]}");
        }
        }
        message('批量发货成功！', order_list_backurl(), 'success');
        }
	if ($_GPC['export'] == 1) {
		ca('order.op.export');
		plog('order.op.export', '导出订单');
		$columns = array(
                    array('title' => '订单编号', 'field' => 'ordersn', 'width' => 24), 
                    array('title' => '收货姓名(或自提人)', 'field' => 'realname', 'width' => 12), 
                    array('title' => '联系电话', 'field' => 'mobile', 'width' => 12), 
                    array('title' => '收货地址', 'field' => 'address', 'width' => 12), 
                    array('title' => '商品名称', 'field' => 'goods_title', 'width' => 24), 
                    array('title' => '商品编码', 'field' => 'goods_goodssn', 'width' => 12), 
                    array('title' => '商品规格', 'field' => 'goods_optiontitle', 'width' => 12), 
                    array('title' => '商品数量', 'field' => 'goods_total', 'width' => 12), 
                    array('title' => '商品单价(折扣前)', 'field' => 'goods_price1', 'width' => 12), 
                    array('title' => '商品单价(折扣后)', 'field' => 'goods_price2', 'width' => 12), 
                    array('title' => '商品价格(折扣前)', 'field' => 'goods_rprice1', 'width' => 12), 
                    array('title' => '商品价格(折扣后)', 'field' => 'goods_rprice2', 'width' => 12),
                    array('title' => '支付方式', 'field' => 'paytype', 'width' => 12), 
                    array('title' => '配送方式', 'field' => 'dispatchname', 'width' => 12), 
                    array('title' => '运费', 'field' => 'dispatchprice', 'width' => 12),
                    array('title' => '优惠券', 'field' => 'youhuiquan', 'width' => 12),
                    array('title' => '礼品抵扣', 'field' => 'gift_card', 'width' => 12),
                    array('title' => '余额抵扣', 'field' => 'goods_deductcredit2', 'width' => 12),
                    array('title' => '直接支付金额', 'field' => 'straight_price', 'width' => 12), 
                    array('title' => '订单类型', 'field' => 'order_type', 'width' => 12), 
                    array('title' => '总订单ID', 'field' => 'TotalId', 'width' => 12),
                    array('title' => '状态', 'field' => 'status', 'width' => 12), 
                    array('title' => '下单时间', 'field' => 'createtime', 'width' => 24), 
                    array('title' => '付款时间', 'field' => 'paytime', 'width' => 24), 
                    array('title' => '发货时间', 'field' => 'sendtime', 'width' => 24), 
                    array('title' => '完成时间', 'field' => 'finishtime', 'width' => 24), 
                    array('title' => '快递公司', 'field' => 'expresscom', 'width' => 24), 
                    array('title' => '快递单号', 'field' => 'expresssn', 'width' => 24), 
                    array('title' => '订单备注', 'field' => 'remark', 'width' => 36), 
                    array('title' => '寄件人', 'field' => 'sender', 'width' => 36), 
                    array('title' => '寄件地址', 'field' => 'sender_address', 'width' => 36), 
                    array('title' => '寄件人电话', 'field' => 'sender_phone', 'width' => 36));
                if (!empty($agentid) && $level > 0){
			$columns[] = array('title' => '分销级别', 'field' => 'level', 'width' => 24);
			$columns[] = array('title' => '分销佣金', 'field' => 'commission', 'width' => 24);
		}
		foreach ($list as &$row) {
			$row['ordersn'] = $row['ordersn'] . " ";
			$row['expresssn'] = $row['expresssn'] . " ";
			$row['createtime'] = date('Y-m-d H:i:s', $row['createtime']);
			$row['paytime'] = !empty($row['paytime']) ? date('Y-m-d H:i:s', $row['paytime']) : '';
			$row['sendtime'] = !empty($row['sendtime']) ? date('Y-m-d H:i:s', $row['sendtime']) : '';
			$row['finishtime'] = !empty($row['finishtime']) ? date('Y-m-d H:i:s', $row['finishtime']) : '';
		}
		unset($row);
		$exportlist = array();
		foreach ($list as &$r){
			$ogoods = $r['goods'];
			unset($r['goods']);
			foreach ($ogoods as $k => $g) {
                                if($r['TotalId']>1){
                                  $r['order_type']="子订单";
                                }
                                if($r['TotalId']==1){
                                  $r['order_type']="总订单";
                                  $r['TotalId']=$r['id'];
                                }
                                if($r['TotalId']==0){
                                  $r['order_type']="普通订单";
                                  $r['TotalId']=" ";
                                }
				if ($k > 0) {
					$r['ordersn'] = '';
					$r['realname'] = '';
					$r['mobile'] = '';
					$r['address'] = '';
					$r['paytype'] = '';
					$r['dispatchname'] = '';
					$r['dispatchprice'] = '';
					$r['price'] = '';
					$r['status'] = '';
					$r['createtime'] = '';
					$r['sendtime'] = '';
					$r['finishtime'] = '';
					$r['expresscom'] = '';
					$r['expresssn'] = '';
					$r['remark'] = '';
                                        $r['order_type']="总订单";
				}
                                if($r['price'] < 0){
                                  $r['goods_deductcredit2']=$r['price']+$r['deductcredit2'];
                                  $r['straight_price']=0;
                                }else{
                                   $r['goods_deductcredit2']=$r['deductcredit2'];
                                   $r['straight_price']=$r['price'];
                                }
				$r['goods_title'] = $g['title'];
				$r['goods_goodssn'] = $g['goodssn'];
				$r['goods_optiontitle'] = $g['optiontitle'];
				$r['goods_total'] = $g['total'];
				$r['goods_price1'] = $g['price'] / $g['total'];
				$r['goods_price2'] = $g['realprice'] / $g['total'];
				$r['goods_rprice1'] = $g['price'];
				$r['goods_rprice2'] = $g['realprice'];
				$r['sender'] = '孙小妖';
				$r['sender_address'] = '吉林省通化市辉南县扶民镇四岔子屯马宝昌林下参场';
				$r['sender_phone'] = '18958007412';
				$exportlist[] = $r;
			} 
		}                
		unset($r);
		m('excel')->export($exportlist, array("title" => "普通订单数据-" . date('Y-m-d-H-i', time()), "columns" => $columns));
	}
	$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('ewei_shop_order') . " o " . " left join " . tablename('ewei_shop_order_refund') . " r on r.orderid=o.id" . " left join " . tablename('ewei_shop_member') . " m on m.openid=o.openid " . " left join " . tablename('ewei_shop_member_address') . " a on o.addressid = a.id " . " WHERE {$condition}", $paras);
	$totalmoney = pdo_fetchcolumn('SELECT sum(o.price) FROM ' . tablename('ewei_shop_order') . " o " . " left join " . tablename('ewei_shop_order_refund') . " r on r.orderid=o.id" . " left join " . tablename('ewei_shop_member') . " m on m.openid=o.openid  " . " left join " . tablename('ewei_shop_member_address') . " a on o.addressid = a.id " . " WHERE o.status>=1 and o.deleted=0 and {$condition}", $paras);
	$pager = pagination($total, $pindex, $psize);
	load()->func('tpl');
	include $this->template('web/allorder/normal_list');
	die;
} elseif ($operation == 'detail') {
	$id = intval($_GPC['id']);
	$item = pdo_fetch("SELECT * FROM " . tablename('ewei_shop_order') . " WHERE id = :id and uniacid=:uniacid", array(':id' => $id, ':uniacid' => $_W['uniacid']));
	$item['statusvalue'] = $item['status'];
	$shopset = m('common')->getSysset('shop');
	if (empty($item)) {
		message("抱歉，订单不存在!", referer(), "error");
	}
	if (!empty($item['refundid'])) {
		ca('order.view.status4');
	} else {
		if ($item['status'] == -1) {
			ca('order.view.status_1');
		} else {
			ca('order.view.status' . $item['status']);
		}
	}
	$member = m('member')->getInfo($item['openid']);
	$dispatch = pdo_fetch("SELECT * FROM " . tablename('ewei_shop_dispatch') . " WHERE id = :id and uniacid=:uniacid", array(':id' => $item['dispatchid'], ':uniacid' => $_W['uniacid']));
        $dispatches = pdo_fetchall("SELECT * FROM " . tablename('ewei_shop_dispatch') . " WHERE  uniacid=:uniacid", array(':uniacid' => $_W['uniacid']));
	if (empty($item['addressid'])) {
		$user = unserialize($item['carrier']);
	} else {
		$user = pdo_fetch("SELECT * FROM " . tablename('ewei_shop_member_address') . " WHERE id = :id and uniacid=:uniacid", array(':id' => $item['addressid'], ':uniacid' => $_W['uniacid']));
		$user['address'] = $user['province'] . ' ' . $user['city'] . ' ' . $user['area'] . ' ' . $user['address'];
	}
        if(!empty($_GPC['changemessage'])){
        $order=pdo_fetch("select * from ".tablename("ewei_shop_order")." where uniacid=:uniacid  and id=:id",array(":uniacid"=>$_W['uniacid'],"id"=>$_GPC['id']));
        if($order['TotalId'] > 1){
        message('子订单不能修改发货信息！',referer(), 'error');
        }
        $data=array(
           "uniacid"=>$_W['uniacid'],
           "openid"=>$_GPC['user_openid'],
            "realname"=>$_GPC['realname'],
            "mobile"=>$_GPC['mobile'],
            'province'=>$_GPC['province'],
            'city'=>$_GPC['city'],
            'area'=>$_GPC["area"],
            "address"=>$_GPC['address'],
            'isdefault'=>0,
            'deleted'=>1,
            "old_id"=>$_GPC['old_id']
        );
        pdo_insert("ewei_shop_member_address",$data);
        $addressid=pdo_insertid();
        pdo_update("ewei_shop_order",array("addressid"=>$addressid),array("uniacid"=>$_W['uniacid'],"id"=>$_GPC["id"],"openid"=>$_GPC['user_openid']));//修改普通订单和总订单的发货信息
        //修改子订单的发货信息
        $orderes=pdo_fetchall("select * from ".tablename("ewei_shop_order")." where uniacid=:uniacid and TotalId=:TotalId and openid=:openid",array(":uniacid"=>$_W['uniacid'],":TotalId"=>$_GPC["id"],":openid"=>$_GPC['user_openid']));
        foreach($orderes as $key=>$value){
        pdo_update("ewei_shop_order",array("addressid"=>$addressid),array("uniacid"=>$_W['uniacid'],"id"=>$value["id"]));//修改子订单的发货信息
        }
        message('修改发货信息成功！',referer(), 'success');
        }
        //修改运费
        if($_POST['dispatch']=="free"){
            if($item['dispatchprice'] == 0){
            exit;
            }
            $dispatchid=0;
            if($item['deductcredit2']>0 && $item['price'] <=0){
                $dedu=$item['deductcredit2']-$item['dispatchprice'];
                pdo_update('ewei_shop_order',array('dispatchid' =>$dispatchid,'dispatchprice'=>0,'deductcredit2'=>$dedu),array('id' => $id, 'uniacid' => $_W['uniacid']));
            }
            if($item['deductcredit2']==0 && !empty($item['price'])){
                $price=$item['price']-$item['dispatchprice'];
                pdo_update('ewei_shop_order',array('dispatchid' =>$dispatchid,'dispatchprice'=>0,'price'=>$price),array('id' => $id, 'uniacid' => $_W['uniacid']));
            }
            if($item['deductcredit2']>0 && $item['price'] >0){
                if($item['price']>=$item['dispatchprice']){
                 $price=$item['price']-$item['dispatchprice'];
                 pdo_update('ewei_shop_order',array('dispatchid' =>$dispatchid,'dispatchprice'=>0,'price'=>$price),array('id' => $id, 'uniacid' => $_W['uniacid']));
                }else{
                 $dedu=$item['deductcredit2']+$item['price']-$item['dispatchprice'];
                 pdo_update('ewei_shop_order',array('dispatchid' =>$dispatchid,'dispatchprice'=>0,'price'=>0,'deductcredit2'=>$dedu),array('id' => $id, 'uniacid' => $_W['uniacid']));
                }
            }
                $data=array(
                'uniacid' => $_W['uniacid'],
                'openid' => $item['openid'],
                'ordersn' => $item['ordersn'],
                'price' => $item['price'],
                'dispatchprice' => $item['dispatchprice'],
                'dispatchid' => $item['dispatchid'],
                'deductcredit2' => $item['deductcredit2'],
                'createtime' =>time()
                );
                pdo_insert('ewei_shop_dispatchprice_free_log', $data);
                exit;
        }
        //修改订单状态
        if(array_key_exists('editor_status',$_POST)){
            if($_POST['editor_status']!=4){
            pdo_update('ewei_shop_order',array('status' =>$_POST['editor_status']),array('id' => $id, 'uniacid' => $_W['uniacid']));
            }
            //退款订单修改成已退款
            if($_POST['editor_status']==4){
            $order_info=pdo_fetch('select * from '.tablename('ewei_shop_order').' where uniacid=:uniacid and id=:id',array(':uniacid'=> $_W['uniacid'],':id'=>$id));
            pdo_update('ewei_shop_order_refund', array('reply' => '', 'status' => 1, 'refundtype' =>2), array('id' => $order_info['refundid']));
            pdo_update('ewei_shop_order', array('refundid' => 0, 'status' => -1, 'refundtime' =>time()), array('id' =>$id, 'uniacid' => $_W['uniacid']));
            }
        exit;
        }
	$refund = pdo_fetch("SELECT * FROM " . tablename('ewei_shop_order_refund') . " WHERE orderid = :orderid and uniacid=:uniacid order by id desc", array(':orderid' => $item['id'], ':uniacid' => $_W['uniacid']));
	$goods = pdo_fetchall("SELECT g.*, o.goodssn as option_goodssn, o.productsn as option_productsn,o.total,g.type,o.optionname,o.optionid,o.price as orderprice,o.realprice FROM " . tablename('ewei_shop_order_goods') . " o left join " . tablename('ewei_shop_goods') . " g on o.goodsid=g.id " . " WHERE o.orderid=:orderid and o.uniacid=:uniacid", array(':orderid' => $id, ':uniacid' => $_W['uniacid']));
	foreach ($goods as &$r) {
		if (!empty($r['option_goodssn'])) {
			$r['goodssn'] = $og['option_goodssn'];
		}
		if (!empty($og['option_productsn'])) {
			$r['productsn'] = $og['option_productsn'];
		}
	}
	unset($r);
	$item['goods'] = $goods;
	$agents = array();
	if (p('commission')) {
		$agents = p('commission')->getAgents($id);
	}
	load()->func('tpl');
	include $this->template('web/allorder/normal_detail');
	die;
} elseif ($operation == 'delete') {
	ca('order.op.delete');
	$orderid = intval($_GPC['id']);
	pdo_update('ewei_shop_order', array('deleted' => 1), array('id' => $orderid, 'uniacid' => $_W['uniacid']));
	plog('order.op.delete', "订单删除 ID: {$id}");
	message('订单删除成功', $this->createWebUrl('allorder', array('op' => 'display')), 'success');
} elseif ($operation == 'deal') {
	$id = intval($_GPC['id']);
	$item = pdo_fetch("SELECT * FROM " . tablename('ewei_shop_order') . " WHERE id = :id and uniacid=:uniacid", array(':id' => $id, ':uniacid' => $_W['uniacid']));
	$shopset = m('common')->getSysset('shop');
	if (empty($item)) {
		message("抱歉，订单不存在!", referer(), "error");
	}
	if (!empty($item['refundid'])) {
		ca('order.view.status4');
	} else {
		if ($item['status'] == -1) {
			ca('order.view.status_1');
		} else {
			ca('order.view.status' . $item['status']);
		}
	}
	$to = trim($_GPC['to']);
	if ($to == 'confirmpay') {
		order_list_confirmpay($item);
	} else {
		if ($to == 'cancelpay') {
			order_list_cancelpay($item);
		} else {
			if ($to == 'confirmsend') {
				order_list_confirmsend($item);
			} else {
				if ($to == 'cancelsend') {
					order_list_cancelsend($item);
				} else {
					if ($to == 'confirmsend1') {
						order_list_confirmsend1($item);
					} else {
						if ($to == 'cancelsend1') {
							order_list_cancelsend1($item);
						} else {
							if ($to == 'finish') {
								order_list_finish($item);
							} else {
								if ($to == 'close') {
									order_list_close($item);
								} else {
									if ($to == 'refund') {
										order_list_refund($item);
									}
								}
							}
						}
					}
				}
			}
		}
	}
	die;
}
function changeWechatSend($ordersn, $status, $msg = '')
{
	global $_W;
	$paylog = pdo_fetch("SELECT plid, openid, tag FROM " . tablename('core_paylog') . " WHERE tid = '{$ordersn}' AND status = 1 AND type = 'wechat'");
	if (!empty($paylog['openid'])) {
		$paylog['tag'] = iunserializer($paylog['tag']);
		$acid = $paylog['tag']['acid'];
		load()->model('account');
		$account = account_fetch($acid);
		$payment = uni_setting($account['uniacid'], 'payment');
		if ($payment['payment']['wechat']['version'] == '2') {
			return true;
		}
		$send = array('appid' => $account['key'], 'openid' => $paylog['openid'], 'transid' => $paylog['tag']['transaction_id'], 'out_trade_no' => $paylog['plid'], 'deliver_timestamp' => TIMESTAMP, 'deliver_status' => $status, 'deliver_msg' => $msg);
		$sign = $send;
		$sign['appkey'] = $payment['payment']['wechat']['signkey'];
		ksort($sign);
		$string = '';
		foreach ($sign as $key => $v) {
			$key = strtolower($key);
			$string .= "{$key}={$v}&";
		}
		$send['app_signature'] = sha1(rtrim($string, '&'));
		$send['sign_method'] = 'sha1';
		$account = WeAccount::create($acid);
		$response = $account->changeOrderStatus($send);
		if (is_error($response)) {
			message($response['message']);
		}
	}
}
function order_list_backurl()
{
	global $_GPC;
	return $_GPC['op'] == 'detail' ? $this->createWebUrl('allorder') : referer();
}
function order_list_confirmsend($item)
{          
	global $_W, $_GPC;
	ca('order.op.send');
	if ($item['status'] != 1) {
		message('订单未付款，无法发货！');
	}
	if (!empty($_GPC['isexpress']) && empty($_GPC['expresssn'])) {
		message('请输入快递单号！');
	}
	if (!empty($item['transid'])) {
		changeWechatSend($item['ordersn'], 1);
	}
	pdo_update('ewei_shop_order', array('status' => 2, 'remark' => trim($_GPC['remark']), 'express' => trim($_GPC['express']), 'expresscom' => trim($_GPC['expresscom']), 'expresssn' => trim($_GPC['expresssn']), 'sendtime' => time()), array('id' => $item['id'], 'uniacid' => $_W['uniacid']));
	if (!empty($item['refundid'])) {
		$refund = pdo_fetch('select * from ' . tablename('ewei_shop_order_refund') . ' where id=:id limit 1', array(':id' => $item['refundid']));
		if (!empty($refund)) {
			pdo_update('ewei_shop_order_refund', array('status' => -1), array('id' => $item['refundid']));
			pdo_update('ewei_shop_order', array('refundid' => 0), array('id' => $item['id']));
		}
	}
	m('notice')->sendOrderMessage($item['id']);
	plog('order.op.send', "订单发货 ID: {$item['id']} 订单号: {$item['ordersn']} <br/>快递公司: {$_GPC['expresscom']} 快递单号: {$_GPC['expresssn']}");
	message('发货操作成功！', order_list_backurl(), 'success');
}
function order_list_confirmsend1($item)
{
	global $_W, $_GPC;
	ca('order.op.fetch');
	if ($item['status'] != 1) {
		message('订单未付款，无法确认取货！');
	}
	$time = time();
	$d = array('status' => 3, 'sendtime' => $time, 'finishtime' => $time, 'remark' => $_GPC['remark']);
	if ($item['isverify'] == 1) {
		$d['verified'] = 1;
		$d['verifytime'] = $time;
		$d['verifyopenid'] = "";
	}
	pdo_update('ewei_shop_order', $d, array('id' => $item['id'], 'uniacid' => $_W['uniacid']));
	if (!empty($item['refundid'])) {
		$refund = pdo_fetch('select * from ' . tablename('ewei_shop_order_refund') . ' where id=:id limit 1', array(':id' => $item['refundid']));
		if (!empty($refund)) {
			pdo_update('ewei_shop_order_refund', array('status' => -1), array('id' => $item['refundid']));
			pdo_update('ewei_shop_order', array('refundid' => 0), array('id' => $item['id']));
		}
	}
	m('member')->upgradeLevel($item['openid']);
	m('notice')->sendOrderMessage($item['id']);
	if (p('commission')) {
		p('commission')->checkOrderFinish($item['id']);
	}
	plog('order.op.fetch', "订单确认取货 ID: {$item['id']} 订单号: {$item['ordersn']}");
	message('发货操作成功！', order_list_backurl(), 'success');
}
function order_list_cancelsend($item)
{
	global $_W, $_GPC;
	ca('order.op.sendcancel');
	if ($item['status'] != 2) {
		message('订单未发货，不需取消发货！');
	}
	if (!empty($item['transid'])) {
		changeWechatSend($item['ordersn'], 0, $_GPC['cancelreson']);
	}
	pdo_update('ewei_shop_order', array('status' => 1, 'sendtime' => 0, 'remark' => $_GPC['remark']), array('id' => $item['id'], 'uniacid' => $_W['uniacid']));
	plog('order.op.sencancel', "订单取消发货 ID: {$item['id']} 订单号: {$item['ordersn']}");
	message('取消发货操作成功！', order_list_backurl(), 'success');
}
function order_list_cancelsend1($item)
{
	global $_W, $_GPC;
	ca('order.op.fetchcancel');
	if ($item['status'] != 3) {
		message('订单未取货，不需取消！');
	}
	pdo_update('ewei_shop_order', array('status' => 1, 'finishtime' => 0, 'remark' => trim($_GPC['remark'])), array('id' => $item['id'], 'uniacid' => $_W['uniacid']));
	plog('order.op.fetchcancel', "订单取消取货 ID: {$item['id']} 订单号: {$item['ordersn']}");
	message('取消发货操作成功！', order_list_backurl(), 'success');
}
function order_list_finish($item)
{
	global $_W, $_GPC;
	ca('order.op.finish');
	pdo_update('ewei_shop_order', array('status' => 3, 'finishtime' => time(), 'remark' => $_GPC['remark']), array('id' => $item['id'], 'uniacid' => $_W['uniacid']));
	m('member')->upgradeLevel($item['openid']);
	m('notice')->sendOrderMessage($item['id']);
	if (p('commission')) {
		p('commission')->checkOrderFinish($item['id']);
	}
	plog('order.op.finish', "订单完成 ID: {$item['id']} 订单号: {$item['ordersn']}");
	message('订单操作成功！', order_list_backurl(), 'success');
}
function order_list_cancelpay($item)
{
	global $_W, $_GPC;
	ca('order.op.paycancel');
	m('order')->setStocksAndCredits($item['id'], 2);
	pdo_update('ewei_shop_order', array('status' => 0, 'cancelpaytime' => time(), 'remark' => $_GPC['remark']), array('id' => $item['id'], 'uniacid' => $_W['uniacid']));
	plog('order.op.paycancel', "订单取消付款 ID: {$item['id']} 订单号: {$item['ordersn']}");
	message('取消订单付款操作成功！', order_list_backurl(), 'success');
}
function order_list_confirmpay($item)
{
	global $_W, $_GPC;
	ca('order.op.pay');
	pdo_update('ewei_shop_order', array('status' => 1, 'paytype' => 11, 'paytime' => time(), 'remark' => $_GPC['remark']), array('id' => $item['id'], 'uniacid' => $_W['uniacid']));
	m('order')->setStocksAndCredits($item['id'], 1);
	m('notice')->sendOrderMessage($item['id']);
	if (p('commission')) {
		p('commission')->checkOrderPay($item['id']);
	}
	plog('order.op.pay', "订单确认付款 ID: {$item['id']} 订单号: {$item['ordersn']}");
	message('确认订单付款操作成功！', order_list_backurl(), 'success');
}
function order_list_close($item)
{
	global $_W, $_GPC;
	ca('order.op.close');
	if (!empty($item['transid'])) {
		changeWechatSend($item['ordersn'], 0, $_GPC['reson']);
	}
	pdo_update('ewei_shop_order', array('status' => -1, 'canceltime' => time(), 'remark' => $_GPC['remark']), array('id' => $item['id'], 'uniacid' => $_W['uniacid']));
	if ($item['deductprice'] > 0) {
		m('member')->setCredit($item['openid'], 'credit1', $item['deductcredit'], array('0', $shopset['name'] . "购物返还抵扣积分 积分: {$item['deductcredit']} 抵扣金额: {$item['deductprice']} 订单号: {$item['ordersn']}"));
	}
	plog('order.op.close', "订单关闭 ID: {$item['id']} 订单号: {$item['ordersn']}");
	message('订单关闭操作成功！', order_list_backurl(), 'success');
}
function order_list_refund($item)
{      
	global $_W, $_GPC;
	ca('order.op.refund');
	$shopset = m('common')->getSysset('shop');
	if (empty($item['refundid'])) {
		message('订单未申请退款，不需处理！');
	}
	$refund = pdo_fetch('select * from ' . tablename('ewei_shop_order_refund') . ' where id=:id and status=0 limit 1', array(':id' => $item['refundid']));
	if (empty($refund)) {
		pdo_update('ewei_shop_order', array('refundid' => 0), array('id' => $item['id'], 'uniacid' => $_W['uniacid']));
		message('未找到退款申请，不需处理！');
	}
	if (empty($refund['refundno'])) {
		$refund['refundno'] = m('common')->createNO('order_refund', 'refundno', 'SR');
		pdo_update('ewei_shop_order_refund', array('refundno' => $refund['refundno']), array('id' => $refund['id']));
	}
	$refundstatus = intval($_GPC['refundstatus']);
	$refundcontent = $_GPC['refundcontent'];
	if ($refundstatus == 0) {
		message('暂不处理', referer());
	} else {
		if ($refundstatus == 1) {
			$realprice = $_GPC['refundmoney'];
			$goods = pdo_fetchall("SELECT g.credit, o.total,o.realprice FROM " . tablename('ewei_shop_order_goods') . " o left join " . tablename('ewei_shop_goods') . " g on o.goodsid=g.id " . " WHERE o.orderid=:orderid and o.uniacid=:uniacid", array(':orderid' => $item['id'], ':uniacid' => $_W['uniacid']));
			$credits = 0;
			foreach ($goods as $g) {
				$credits += $g['credit'] * $g['total'];
			}
			$refundtype = 0;
			if ($item['paytype'] == 1) {
				m('member')->setCredit($item['openid'], 'credit2', $realprice, array(0, $shopset['name'] . "退款: {$realprice}元 订单号: " . $item['ordersn']));
				$result = true;
			} else {
				if ($item['paytype'] == 21) {
					$realprice = round($realprice - $item['deductcredit2'], 2);
					$result = m('finance')->refund($item['openid'], $item['ordersn'], $refund['refundno'], $realprice * 100);
					$refundtype = 2;
				} else {
					if ($realprice < 1) {
						message('退款金额必须大于1元，才能使用微信企业付款退款!', '', 'error');
					}
					$realprice = round($realprice - $item['deductcredit2'], 2);
					$result = m('finance')->pay($item['openid'], 1, $realprice * 100, $refund['refundno'], $shopset['name'] . "退款: {$realprice}元 订单号: " . $item['ordersn']);
					$refundtype = 1;
				}
			}
			if (is_error($result)) {
				message($result['message'], '', 'error');
			}
			m('member')->setCredit($item['openid'], 'credit1', -$credits, array(0, $shopset['name'] . "退款扣除积分: {$credits} 订单号: " . $item['ordersn']));
			if ($item['deductcredit'] > 0) {
				m('member')->setCredit($item['openid'], 'credit1', $item['deductcredit'], array('0', $shopset['name'] . "购物返还抵扣积分 积分: {$item['deductcredit']} 抵扣金额: {$item['deductprice']} 订单号: {$item['ordersn']}"));
			}
			if (!empty($refundtype)) {
				if ($item['deductcredit2'] > 0) {
					m('member')->setCredit($item['openid'], 'credit2', $item['deductcredit2'], array('0', $shopset['name'] . "购物返还抵扣余额 积分: {$item['deductcredit2']} 订单号: {$item['ordersn']}"));
				}
			}
			pdo_update('ewei_shop_order_refund', array('reply' => '', 'status' => 1, 'refundtype' => $refundtype), array('id' => $item['refundid']));
			m('notice')->sendOrderMessage($item['id'], true);
			pdo_update('ewei_shop_order', array('refundid' => 0, 'status' => -1, 'refundtime' => time()), array('id' => $item['id'], 'uniacid' => $_W['uniacid']));
			plog('order.op.refund', "订单退款 ID: {$item['id']} 订单号: {$item['ordersn']}");
		} else {
			if ($refundstatus == -1) {
				pdo_update('ewei_shop_order_refund', array('reply' => $refundcontent, 'status' => -1), array('id' => $item['refundid']));
				m('notice')->sendOrderMessage($item['id'], true);
				plog('order.op.refund', "订单退款拒绝 ID: {$item['id']} 订单号: {$item['ordersn']} 原因: {$refundcontent}");
				pdo_update('ewei_shop_order', array('refundid' => 0), array('id' => $item['id'], 'uniacid' => $_W['uniacid']));
			}
		}
	}
	message('退款申请处理成功!', order_list_backurl(), 'success');
}
if (p('commission')) {
	$com_set = p('commission')->getSet();
}